package com.example.ui.share;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.entity.BlogPic;
import com.example.entity.CircleMember;
import com.example.entity.CircleShareEntity;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.AnalyzingJson;
import com.example.net.Communication;
import com.example.net.NetRequest;
import com.example.service.MainService;
import com.example.ui.contact.face.FaceUtil;
import com.example.ui.homepage.HomePageView;
import com.example.ui.leftmenu.MyListView;
import com.example.util.BitmapLoad;
import com.example.util.PullDownView;
import com.example.util.Util;

public class CircleHomeActivity extends Activity {
	public static Handler handler;
	public static final int FAIL = 0;
	public static final int SUCCESS=1;
	public static final int JOIN_SUCCESS=2;
	public static final int JOIN_WAIT=3;
	public static final int JOIN_FAIL=4;
	
	private Button titleLeftBtn,titleRightBtn;
	private TextView titleText;
	private MyListView listview;
	private PullDownView mPullDownView;
	private ImageView bottomLeftPhontBtn,bottomRightCameraBtn;
	private Button bottomPublishCommentBtn;
	//加载时 相关控件
	private LinearLayout loadLayout;
	private ProgressBar loadProgressBar;
	private ImageView loadImg;
	// 头布局文件
	private View headView;
	private LinearLayout circleHeadLayout;
	private LinearLayout homePageIntroduceLayout;
	private ImageView headImg;
	private TextView titleNameText;
	private TextView circleIntroduce;
	private TextView circleMemberNum;
	private Gallery circleMemberGallery;
	private TextView circleMoreMemberBtn;
	private TextView circleShareNum;
	private String myId =HSApplication.sp.getString("userid","");
	private Intent myIntent;
	private String circleId,typeId,createCircleUserId,headPathStr,titleStr,introStr,circleMemberNumStr,circleShareNumStr;
	public static CircleListAdapter circleAdapter;
	private CircleMemberAdapter circleMemberAdapter;
	private ArrayList<CircleMember> circleMemberList = new ArrayList<CircleMember>();
	private int listCount=0;
	//表情
	FaceUtil faceUtil = HSApplication.getInstance().getFaceUtil();
//	private InputMethodManager imm;
	int typeID;
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private String headPath;
	
	public static List<CircleShareEntity> circleShareEntity;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item05);
		headView = LayoutInflater.from(this).inflate(R.layout.homepage_head,null);

		myIntent = getIntent();
		circleId= myIntent.getStringExtra("circleId").toString();
		typeId = myIntent.getStringExtra("typeId").toString();
		createCircleUserId = myIntent.getStringExtra("createCircleUserId").toString();
		headPathStr = myIntent.getStringExtra("headImg").toString();
		titleStr = myIntent.getStringExtra("titleName").toString();
		introStr = myIntent.getStringExtra("intro").toString();
		circleMemberNumStr = myIntent.getStringExtra("circleMemberNum").toString();
		circleShareNumStr = myIntent.getStringExtra("circleShareNum").toString();
		headPath=HSApplication.sp.getString("imgHead","").toString();
		findView();
		getCircleMember();
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case FAIL:
					Util.toast(CircleHomeActivity.this, "网络连接失败");
					break;
				case SUCCESS:
					circleAdapter = new CircleListAdapter();
					listview.setAdapter(circleAdapter);
					break;
				case JOIN_SUCCESS://typeId=1,自由加入
					Util.toast(CircleHomeActivity.this, "申请成功");
					break;
				case JOIN_WAIT://typeId=0,需要申请
					Util.toast(CircleHomeActivity.this, "您的申请已经提交，请等待审核...");
					break;
				case JOIN_FAIL://typeId=100,禁止加入
					Util.toast(CircleHomeActivity.this, "该圈子已被限制加入");
					break;

				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}


	private void findView() {
		titleLeftBtn=(Button)findViewById(R.id.layout_title_left_btn);
		titleRightBtn=(Button)findViewById(R.id.layout_title_right_btn);
		titleText=(TextView)findViewById(R.id.layout_title_middle_text);
		loadLayout=(LinearLayout)findViewById(R.id.load_layout);
		loadProgressBar=(ProgressBar)findViewById(R.id.load_progressbar);
		loadImg = (ImageView)findViewById(R.id.load_logo_img);
		listview = (MyListView)findViewById(R.id.item05_mylistview);
		mPullDownView=(PullDownView)findViewById(R.id.item05_listview);
		circleHeadLayout=(LinearLayout)headView.findViewById(R.id.circle_home_head_layout);
		homePageIntroduceLayout=(LinearLayout)headView.findViewById(R.id.homepage_layout);
		headImg = (ImageView)headView.findViewById(R.id.homepage_head_img);
		titleNameText=(TextView)headView.findViewById(R.id.homepage_name_text);
		circleIntroduce=(TextView)headView.findViewById(R.id.circle_home_introduce);
		circleMemberNum=(TextView)headView.findViewById(R.id.circle_member_text_num);
		circleMemberGallery=(Gallery)headView.findViewById(R.id.cicle_member_gallery);
		circleMoreMemberBtn=(TextView)headView.findViewById(R.id.circle_more_member_btn);
		circleShareNum=(TextView)headView.findViewById(R.id.circle_share_text_num);
		bottomLeftPhontBtn=(ImageView)findViewById(R.id.layout_bottom_photo_album);
		bottomPublishCommentBtn=(Button)findViewById(R.id.layout_bottom_publish_comment_edit);
		bottomRightCameraBtn=(ImageView)findViewById(R.id.layout_bottom_camera);
		bottomPublishCommentBtn.setText("分享点什么吧");
		init();
		listView();
		bottomClick();
	}

	private void init() {
		titleLeftBtn.setText("返回");
		titleText.setText("圈子主页");
		if(myId.equals(createCircleUserId)){
			titleRightBtn.setText("圈子管理");
		}else{
			titleRightBtn.setText("申请加入");
		}
		circleMoreMemberBtn.setText("更多成员");
		circleMoreMemberBtn.setOnClickListener(click);
		titleLeftBtn.setOnClickListener(click);
		titleRightBtn.setOnClickListener(click);
		circleHeadLayout.setVisibility(View.VISIBLE);
		homePageIntroduceLayout.setVisibility(View.GONE);
		headImg.setImageBitmap(BitmapLoad.loadBitmap(this, headPathStr));
		titleNameText.setText(titleStr);
		circleIntroduce.setText(introStr);
		if("".equals(circleMemberNumStr)||circleMemberNumStr==null){
			circleMemberNumStr="0";
		}
		if("".equals(circleShareNumStr)||circleShareNumStr==null){
			circleShareNumStr="0";
		}
		circleMemberNum.setText("圈子成员（"+circleMemberNumStr+"）");
		circleShareNum.setText("圈子分享（"+circleShareNumStr+"）");
		loadLayout.setVisibility(View.GONE);
		listview.setVisibility(View.VISIBLE);
		mPullDownView.setVisibility(View.GONE);
	}

	
	private void listView() {
		listview.addHeaderView(headView);
		Communication.getCircleShare(circleId, listCount);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int po,
					long arg3) {
				int position = po-2;
				Intent intent = new Intent(CircleHomeActivity.this, CircleShareContentActivity.class);
				intent.putExtra("circleId", circleId);
				intent.putExtra("myId", circleShareEntity.get(position).getUid().toString());
				intent.putExtra("blogId", circleShareEntity.get(position).getId().toString());
				intent.putExtra("headImg", circleShareEntity.get(position).getHeadPic().toString());
				intent.putExtra("name", circleShareEntity.get(position).getNickName().toString());
				intent.putExtra("time", circleShareEntity.get(position).getTimeline()+"");
				intent.putExtra("content", circleShareEntity.get(position).getTxt().toString());
				intent.putExtra("position", circleShareEntity.get(position).getPosition().toString());
				intent.putExtra("like", circleShareEntity.get(position).getLike());
				intent.putExtra("reply", circleShareEntity.get(position).getReply());
				intent.putExtra("forward", circleShareEntity.get(position).getForward());
				
				List<String> img = new ArrayList<String>();
				List<BlogPic> bpImg = circleShareEntity.get(position).getPicList();
				if(null!=bpImg){
					for(int i=0;i<bpImg.size();i++){
						String pic = bpImg.get(i).getThumb().toString();
						img.add(pic);
					}
					int imgSize = img.size();
					String[] imgArr = (String[]) img.toArray(new String[imgSize]);
					intent.putExtra("imgArr", imgArr);//上传的图片数组
				}
				
				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onRestart() {
		listview.invalidate();
		circleAdapter.notifyDataSetChanged();
		super.onRestart();
	}

	/**
	 * 圈子成员
	 */
	private void getCircleMember() {
		String memberDada = NetRequest.getCircleMember(circleId,HSApplication.sp.getString("userid",""));
		String result = "" ;
		JSONObject jo;
		try {
			jo = new JSONObject(memberDada);
			result = jo.getString("response");
			if (result.equals("true")) {
				circleMemberList = AnalyzingJson.getCircleMember(memberDada);
				
			} else {
				//h.sendEmptyMessage(1);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		circleMemberAdapter = new CircleMemberAdapter();
		circleMemberGallery.setAdapter(circleMemberAdapter);
		alignGalleryToLeft(circleMemberGallery);//居左显示gallery
	}

	OnClickListener click = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.layout_title_left_btn:
				finish();
				break;
			case R.id.layout_title_right_btn:
				if("圈子管理".equals(titleRightBtn.getText().toString())){
					Intent intent = new Intent(CircleHomeActivity.this, CreateCircleGroupActivity.class);
					intent.putExtra("create_update", "update");
					
					intent.putExtra("headImg", headPathStr);
					intent.putExtra("titleName", titleStr);
					intent.putExtra("intro", introStr);
					
					startActivity(intent);
				}else if("申请加入".equals(titleRightBtn.getText().toString())){
					//Util.toast(CircleHomeActivity.this, "您的申请已经提交，请等待审核...");
					Communication.waitJoin(circleId, HSApplication.sp.getString("userid",""),typeId);
				}
				
				break;
			case R.id.circle_more_member_btn:
				Intent intent = new Intent(CircleHomeActivity.this, CircleMemberActivity.class);
				intent.putExtra("circleId", circleId);
				startActivity(intent);
				break;

			default:
				break;
			}
			
		}
	};

	/**
	 * 发表圈子分享
	 */
	private void bottomClick() {
		bottomLeftPhontBtn.setOnClickListener(new OnClickListener() {//相册
			@Override
			public void onClick(View v) {
//				Util.toast(CircleHomeActivity.this, "抱歉,您赞无发表权限");
				Intent publishIntent = new Intent(CircleHomeActivity.this, PublishCircleShareActivity.class);
				publishIntent.putExtra("myHead", headPath);
				publishIntent.putExtra("circleId", circleId);
				publishIntent.putExtra("type", "edit");
				CircleHomeActivity.this.startActivity(publishIntent);
			}
		});
		bottomPublishCommentBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Util.toast(CircleHomeActivity.this, "抱歉,您赞无发表权限");
				Intent publishIntent = new Intent(CircleHomeActivity.this, PublishCircleShareActivity.class);
				publishIntent.putExtra("myHead",headPath);
				publishIntent.putExtra("circleId", circleId);
				publishIntent.putExtra("type", "edit");
				CircleHomeActivity.this.startActivity(publishIntent);
			}
		});
		bottomRightCameraBtn.setOnClickListener(new OnClickListener() {//拍照
			@Override
			public void onClick(View v) {
//				Util.toast(CircleHomeActivity.this, "抱歉,您赞无发表权限");
				Intent publishIntent = new Intent(CircleHomeActivity.this, PublishCircleShareActivity.class);
				publishIntent.putExtra("myHead",headPath);
				publishIntent.putExtra("circleId", circleId);
				publishIntent.putExtra("type", "edit");
				CircleHomeActivity.this.startActivity(publishIntent);
			}
		});
	}
	
	/**
	 * 圈子分享（ListView-Adapter）
	 */
	class CircleListAdapter extends BaseAdapter{
		int count = circleShareEntity.size();
		@Override
		public int getCount() {
			
			return count;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@SuppressLint("SimpleDateFormat")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(CircleHomeActivity.this).inflate(R.layout.circle_share_item, null);
				holder = new ViewHolder();
				
				holder.headImg=(ImageView) convertView.findViewById(R.id.circle_share_item_head_img);
				holder.name=(TextView) convertView.findViewById(R.id.circle_share_item_name_text);
				holder.content=(TextView) convertView.findViewById(R.id.circle_share_item_content_text);
				holder.time=(TextView) convertView.findViewById(R.id.circle_share_item_time_text);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
				
			String imgStr = circleShareEntity.get(position).getHeadPic().toString();
			if(!"".equals(imgStr)||imgStr!=null){
				Bitmap headBit = BitmapLoad.loadBitmap(CircleHomeActivity.this, imgStr);
				holder.headImg.setImageBitmap(headBit);//头像
			}else{
				holder.headImg.setBackgroundResource(R.drawable.head_bg);
			}
				
				holder.name.setText(circleShareEntity.get(position).getNickName().toString());//名字
				String contentStr = circleShareEntity.get(position).getTxt().toString().replaceAll("&prime;", "'");
				holder.content.setText(contentStr);
				try {
					//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					long dataTime = (Integer)circleShareEntity.get(position).getTimeline();
					String time = format.format(dataTime*1000);
					holder.time.setText(Util.DateCompare(time));
				} catch (ParseException e) {
					holder.time.setText("");
					e.printStackTrace();
				}
				
			
			return convertView;
		}
		class ViewHolder{
			
			//圈子分享用到的
			ImageView headImg;//头像
			TextView name;//名字
			TextView content;//内容txt
			TextView time;//时间
			
		}
		
	}
	
	/**
	 * 圈子成员（Gallery-Adapter）
	 */
	class CircleMemberAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return circleMemberList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			Holder holder = null;
			if(convertView == null){
				holder = new Holder();
				convertView = LayoutInflater.from(CircleHomeActivity.this).inflate(R.layout.homepage_gallery_img, null);
				holder.memberHead = (ImageView)convertView.findViewById(R.id.homepage_gallery_img);
//				holder.memberName = (TextView)convertView.findViewById(R.id.circle_member_item_name);
				convertView.setTag(holder);
			}else{
				holder=(Holder)convertView.getTag();
				
			}
			
			
			try {
//				Bitmap bit = null;
				String imgUrl = circleMemberList.get(position).getHeadPic();
				if(imgUrl!=null){
					Bitmap bit=BitmapLoad.loadBitmap(CircleHomeActivity.this,imgUrl);
					Drawable dra = new BitmapDrawable(bit);
					holder.memberHead.setBackgroundDrawable(dra);
				}else{
					holder.memberHead.setBackgroundResource(R.drawable.head_bg);
				}
				
				holder.memberHead.setScaleType(ImageView.ScaleType.CENTER);
				holder.memberHead.setAdjustViewBounds(true);
				holder.memberHead.setLayoutParams(new Gallery.LayoutParams(50,50));

//				holder.memberName.setText(circleMemberList.get(position).getUserName());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			return convertView;  
		}
		
		class Holder{
			//圈子成员里面用到的
			ImageView memberHead;
//			TextView memberName;
		}
		
	}
	
	/**
	 * 设置Gallery默认居左显示
	 * @param gallery
	 */
	@SuppressWarnings("deprecation")
	private void alignGalleryToLeft(Gallery gallery) {
		int galleryWidth =  (this.getWindowManager().getDefaultDisplay().getWidth())-10;// parentView.getWidth();
		int itemWidth = this.getResources().getDimensionPixelSize(R.dimen.fifty_dimen);
		int spacing = this.getResources().getDimensionPixelSize(R.dimen.eight_dimen);
		int offset;
		if (galleryWidth <= itemWidth) {
			offset = galleryWidth / 2 - itemWidth / 2 - spacing;
		} else {
			offset = galleryWidth - itemWidth - 2 * spacing;
		}
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		//mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
		mlp.setMargins(-offset+itemWidth+spacing, mlp.topMargin, mlp.rightMargin,
				mlp.bottomMargin);
		
	}
	

}
